package com.pennywise.service;

import com.pennywise.common.exception.BusinessException;
import com.pennywise.mapper.DictionaryMapper;
import com.pennywise.model.Dictionary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DictionaryService {
    
    private final DictionaryMapper dictionaryMapper;
    
    /**
     * 添加字典
     */
    public void addDictionary(Dictionary dictionary) {
        log.info("添加字典: {}", dictionary);
        validateDictionary(dictionary);
        
        LocalDateTime now = LocalDateTime.now();
        dictionary.setCreateTime(now);
        dictionary.setUpdateTime(now);
        dictionary.setEnabled(true);
        
        dictionaryMapper.insert(dictionary);
        log.info("字典添加成功，ID: {}", dictionary.getId());
    }
    
    /**
     * 更新字典
     */
    public void updateDictionary(Dictionary dictionary) {
        log.info("更新字典: {}", dictionary);
        validateDictionary(dictionary);
        
        dictionary.setUpdateTime(LocalDateTime.now());
        dictionaryMapper.update(dictionary);
        log.info("字典更新成功，ID: {}", dictionary.getId());
    }
    
    /**
     * 删除字典
     */
    public void deleteDictionary(Long id) {
        log.info("删除字典，ID: {}", id);
        dictionaryMapper.deleteById(id);
        log.info("字典删除成功，ID: {}", id);
    }
    
    /**
     * 获取字典详情
     */
    public Dictionary getDictionary(Long id) {
        log.debug("获取字典，ID: {}", id);
        Dictionary dictionary = dictionaryMapper.findById(id);
        if (dictionary == null) {
            log.warn("未找到字典，ID: {}", id);
        }
        return dictionary;
    }
    
    /**
     * 获取指定类型的字典列表
     */
    @Cacheable(value = "dictionary", key = "#type")
    public List<Dictionary> getDictionariesByType(String type) {
        log.debug("获取字典列表，类型: {}", type);
        return dictionaryMapper.findByType(type);
    }
    
    /**
     * 搜索字典
     */
    public List<Dictionary> searchDictionaries(String type, String keyword) {
        log.debug("搜索字典，类型: {}, 关键字: {}", type, keyword);
        return dictionaryMapper.search(type, keyword);
    }
    
    /**
     * 验证字典数据
     */
    private void validateDictionary(Dictionary dictionary) {
        Dictionary existing = dictionaryMapper.findByTypeAndCode(dictionary.getType(), dictionary.getCode());
        if (existing != null && !existing.getId().equals(dictionary.getId())) {
            throw new BusinessException("字典编码已存在");
        }
    }
} 